﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
// add
using System.Windows.Forms;
using System.Xml;
using System.Diagnostics;
using System.IO;
using System.IO.Ports;
using System.Threading;
using System.Reflection;
using System.ComponentModel;
using System.Runtime.Serialization.Formatters.Binary;
using System.Xml;
using System.Xml.Serialization;
using System.Data;
using FormBaseLib;


public enum enumEnvironment { Production, Development, Testing }
//public enum enumEntryMode { Init, View, Add, Update, Query, Browse }
public enum enumOption { P1, P2, P3 }
public enum enumProjectEasyProperty { Test1, Test2, Test3 }


namespace FormBase
{
    internal static class CProject
    {
        public static CApplication mApp = new CApplication();
        //public static CBase mLastError = new CBase();
        public static CFileKeyValue mFileKeyValue = new CFileKeyValue();
        public static CPropertyXML mOption = new CPropertyXML();
        public static enumEnvironment mEnvironment = enumEnvironment.Production;
        public static CProjectXML mCProjectXML = new CProjectXML();
        public static CProjectRun mCProjectRun = new CProjectRun();
        //static string[] msaArgs;
        static CProject()
        {
            //mAction..BeginAction("static CProject() Begin");
            //mTimeStart = DateTime.Now;
            //mTimeRelease = new DateTime(2014, 6, 4, 22, 0, 0);
            //msNamespace = @"http://www.luckstar.com.tw";   //http://tempuri.org/DataSetProjectRun.xsd
            //msCompanyID = "CompanyID";
            //msSystemID = "SystemID";
            //msProjectID = "ProjectID";

            //// Windows predefines:
            //// i.e.
            ////msPathAppStartup = "D:\\...\\FormBase10\\FormBase\\FormBase\\bin\\Debug"
            ////msPathAppDataUserRoaming = "C:\\Users\\honda_chen\\AppData\\Roaming"
            ////msPathAppDataUserAll = "C:\\ProgramData"
            ////msPathAppDataUserLocal = "C:\\Users\\honda_chen\\AppData\\Local"
            ////msPathAppTemp = "C:\\Users\\honda_chen\\AppData\\Local\\Temp\\"
            //msPathDataUserRoaming = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);  // current roaming user
            //msPathDataUserAll = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);  // all user
            //msPathDataUserLocal = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);   // local user only
            //msPathExeRoot = Application.StartupPath; // The .exe Startup Path.
            //msPathTemp = Path.GetTempPath();
            //msPathTemp = msPathTemp.Remove(msPathTemp.Length - 1, 1);  // Consistency with aboves: no "Back-Slash" in suffix.

            //ResetCounter();

            //mAction.BeginAction("static CProject() end");

            //msAssemblyVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString();

            string s1;

            mApp.mbDebug = true;
            mApp.mTimeStart = DateTime.Now;
            mApp.mTimeRelease = new DateTime(2014, 6, 21, 22, 0, 0);
            mApp.msNamespace = @"http://www.luckstar.com.tw";   //http://tempuri.org/DataSetProjectRun.xsd
            mApp.msCompanyID = "CompanyID";
            mApp.msSystemID = "SystemID";
            mApp.msProjectID = "ProjectID";
            mApp.msProductName = Application.ProductName;
            mApp.msProductVersion = Application.ProductVersion;
            mApp.msAssemblyVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString();

            // Windows predefines:
            // i.e.
            //msPathAppStartup = "D:\\...\\FormBase10\\FormBase\\FormBase\\bin\\Debug"
            //msPathAppDataUserRoaming = "C:\\Users\\honda_chen\\AppData\\Roaming"
            //msPathAppDataUserAll = "C:\\ProgramData"
            //msPathAppDataUserLocal = "C:\\Users\\honda_chen\\AppData\\Local"
            //msPathAppTemp = "C:\\Users\\honda_chen\\AppData\\Local\\Temp\\"
            mApp.msPathDataUserRoaming = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);  // current roaming user
            mApp.msPathDataUserAll = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);  // all user
            mApp.msPathDataUserLocal = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);   // local user only
            mApp.msPathExeRoot = Application.StartupPath; // The .exe Startup Path.
            //s1 = Path.GetTempPath();
            //mApp.msPathSystemTemp = s1.Remove(s1.Length - 1, 1);  // Consistency with aboves: no "Back-Slash" in suffix.

            mApp.ResetCounter();
            //mAction.BeginAction("static CProject() Begin");
            mApp.mAction.BeginAction("FormBase.CProject() Begin");


        }
        //public static DateTime mTimeStart { get; private set; }
        ////public static DateTime mTimeEnd { get; private set; }
        //public static DateTime mTimeRelease { get; private set; }
        //public static string msNamespace { get; private set; }
        //public static string msCompanyID { get; private set; }
        //public static string msSystemID { get; private set; }
        //public static string msProjectID { get; private set; }
        //public static string msPathExeRoot { get; private set; }
        //public static string msPathDataUserRoaming { get; private set; }
        //public static string msPathDataUserAll { get; private set; }
        //public static string msPathDataUserLocal { get; private set; }
        //public static string msPathRoot { get; private set; }
        //public static string msPathData { get; private set; }
        //public static string msPathLog { get; private set; }
        //public static string msPathTemp { get; private set; }
        //public static string msPathLastUsed { get; set; }

        //public static string msAssemblyVersion { get; private set; }
        //public static long mlCounter { get; private set; }
        //public static DateTime mTimeResetCounter { get; private set; }

        //public static void SetCurrentCounter(long lLastCounter, DateTime tLastReset)
        //{
        //    mlCounter = lLastCounter;
        //    mTimeResetCounter = tLastReset;
        //}
        //public static void ResetCounter()
        //{
        //    mlCounter = -1;
        //    mTimeResetCounter = DateTime.Now;
        //}
        //public static long GetNextCounter()
        //{
        //    if (mlCounter >= 9999999999)
        //        ResetCounter();

        //    mlCounter++;
        //    return mlCounter;
        //}
        //public static bool IsDebug
        //{
        //    get { return mAction.IsDebug; }
        //    set { mAction.IsDebug = value; }
        //}
        //public static string Message
        //{
        //    get { return mAction.Message; }
        //}
        //public static string MessageLog
        //{
        //    get { return mAction.MessageLog; }
        //}
        public static bool End()
        {
            // EndApp
            SaveConfig();
            //Application.Exit(new CancelEventArgs(false)); // 這個會觸發Event Application_ApplicationExit, 導致重覆執行本段
            return true;
        }

        static void SetDefaultConfig()
        {
            //foreach (string sKey in Enum.GetNames(typeof(enumProjectEasyProperty)))
            //    mFileKeyValue.AddValue(sKey, string.Empty);
        }
        static bool LoadConfig()
        {
            int i1;
            string s1;

            i1 = Properties.Settings.Default.Runtime;
            switch (i1)
            {
                case (int)enumEnvironment.Development:
                    mEnvironment = enumEnvironment.Development;
                    break;
                case (int)enumEnvironment.Testing:
                    mEnvironment = enumEnvironment.Testing;
                    break;
                default:
                    mEnvironment = enumEnvironment.Production;
                    break;
            }


            i1 = Properties.Settings.Default.Debug;
            if (i1 == 1)
                mApp.mbDebug = true;
            else
                mApp.mbDebug = false;

            mApp.msPathRoot = Properties.Settings.Default.PathRoot;
            if (string.IsNullOrEmpty(mApp.msPathRoot))
                mApp.msPathRoot = mApp.msPathExeRoot;


            try 
            {
                // create directory if needed
                mApp.msPathData = mApp.msPathRoot + @"\App_Data";
                if (!Directory.Exists(mApp.msPathData))
                    Directory.CreateDirectory(mApp.msPathData);
            }
            catch (Exception ex)
            {
                CProject.mApp.PopupError(ex.Message);
                return false;
            }
            mApp.msPathLastUsed = Properties.Settings.Default.PathLastUsed;
            if (string.IsNullOrEmpty(mApp.msPathLastUsed))
                mApp.msPathLastUsed = mApp.msPathSystemTemp;

            //msFilename = Properties.Settings.Default.Filename;

            s1 = CProject.mApp.msPathData + @"\ProjectOption.xml";
            if (!mOption.OpenFile(s1, typeof(enumOption)))
            {
                CProject.mApp.PopupError(mOption.Message);
                return false;
            }

            //mEasyProperty.FilePath = Path.GetFullPath(msPathRoot + @"\App_Data\EasyProperty.txt");
            mFileKeyValue.msFile = CProject.mApp.msPathData + @"\AppRun.txt";
            if (!mFileKeyValue.FileLoad())
            {
                //mLastError.SetLastError(mFileKeyValue.msLastError);
                CProject.mApp.PopupError(mFileKeyValue.msLastError);
                //return false;
            }

            // 這兩個檔案盡量跟exe同一個目錄.
            string sFile = string.Format(@"{0}\{1}.xml", mApp.msPathRoot, mApp.msProjectID); ;
            if (!mCProjectXML.Load(sFile))
                mCProjectXML.CreateNewRowDefault();

            string sFileRun = string.Format(@"{0}\{1}-RUN.xml", mApp.msPathRoot, mApp.msProjectID); ;
            if (!mCProjectRun.Load(sFileRun))
                mCProjectRun.CreateNewRowDefault();

            //// 沒設定的話, 使用預設值:
            //if (string.IsNullOrWhiteSpace(mApp.msPathData))
            //    mApp.msPathData = string.Format(@"{0}\{1}", mApp.msPathExeRoot, "App_Data");


            return true;
        }
        public static bool SaveConfig()
        {
            if (mApp.mbDebug)
            {
                Properties.Settings.Default.Debug = 1;
                mApp.mAction.SaveLog();
            }
            else
                Properties.Settings.Default.Debug = 0;

            //Properties.Settings.Default.Filename = msFilename;
            Properties.Settings.Default.Save();

            // save TProject
            //DataSetProject ds2 = new DataSetProject();
            //DataSetProject.TProjectDataTable t2 = ds2.TProject;
            //DataSetProject.TProjectRow r2 = t2.NewTProjectRow();
            //CopyDataRows(mTProjectRow, r2);
            //t2.AddTProjectRow(r2);
            ////ds1.Namespace = "n"; // http://tempuri.org/DataSetProjectRun.xsd
            ////ds1.Namespace = "n"; // http://tempuri.org/DataSetProjectRun.xsd
            ////ds1.Prefix = string.Empty;
            //SaveXML(ds2, @".\App_Data\Project.txt");

            // save TProjectRun
            //mTProjectRunRow.FEndTime = DateTime.Now;
            //DataSetProjectRun ds1 = new DataSetProjectRun();
            //DataSetProjectRun.TProjectRunDataTable t1 = ds1.TProjectRun;
            //DataSetProjectRun.TProjectRunRow r1 = t1.NewTProjectRunRow();
            //CopyDataRows(mTProjectRunRow, r1);
            //t1.AddTProjectRunRow(r1);
            //ds1.Namespace = "n"; // http://tempuri.org/DataSetProjectRun.xsd
            //ds1.Namespace = "n"; // http://tempuri.org/DataSetProjectRun.xsd
            //ds1.Prefix = string.Empty;
            //SaveXML(mdsDataSetProjectRun, @".\App_Data\ProjectRun.txt");


            //if (mdsDataSetProject.HasChanges())
            //    SaveXML(mdsDataSetProject, @".\App_Data\Project.txt");
            // Save ProjectXML only data has changes.
            if (mCProjectXML.HasChanges())
                if (!mCProjectXML.Save())
                {
                    mApp.PopupError(mCProjectXML.msLastError);
                    return false;
                }

            // save ProjectRun anyway.
            if (!mCProjectRun.Save())
            {
                //mApp.PopupError(mCProjectRun.msLastError);
                mApp.PopupError("ERROR: Save() fail.");
                return false;
            }
            return true;
        }
        private static bool CopyDataRows(DataRow rFrom, DataRow rTo)
        {
            // CodeHelper:
            rTo.ItemArray = rFrom.ItemArray.Clone() as object[];
            return true;
        }
        private static void SaveXML(DataSet ds, string sFile)
        {
            File.WriteAllText(sFile, ds.GetXml(), Encoding.UTF8);
        }
        private static void SaveXMLSchema(DataSet ds, string sFile)
        {
            File.WriteAllText(sFile, ds.GetXmlSchema().Replace("utf-16", "utf-8"), Encoding.UTF8);
        }
        public static bool Begin(string[] args)
        {
            mApp.msaArgs = args;
            SetDefaultConfig();
            if (!LoadConfig())
            {
                CProject.mApp.PopupError("LoadConfig() fail!");
                return false;
            }

            // Open log or not ?
            if (mApp.mbDebug)
            {
                // 兩種自訂開啟 (輸出debug資訊到外部檔案)
                // 1: 由app.config設定啟動如下: (固定同一個輸出檔案, 會一直append text上去)
                //<!-- BEGIN: Debug/Trace to file
                //<system.diagnostics>
                //  <trace autoflush="true">
                //    <listeners>
                //      <add name="textListener" type="System.Diagnostics.TextWriterTraceListener" initializeData="trace.log" />
                //      <remove name="Default" />
                //    </listeners>
                //  </trace>
                //</system.diagnostics>
                // END: Debug/Trace to file -->
                // 2: 由自訂的設定檔案, 結合檔案命名邏輯如下: (可依據開啟的時間決定輸出檔名, 較為彈性, 不需要人工進行檔案維護的工作)
                //Debug.Listeners.Clear();
                ////sFile = string.Format("{0}-{1}.log", ProjectID, DateTime.Now.Second.ToString("00"));
                ////TextWriterTraceListener tr2 = new TextWriterTraceListener(File.CreateText(sFile));
                //sFile = string.Format("{0}{1}-{2}.log", Path.GetTempPath(), ProjectID, DateTime.Now.Second.ToString("00"));
                //TextWriterTraceListener tr2 = new TextWriterTraceListener(File.CreateText(sFile));
                //Debug.Listeners.Add(tr2);
                //Debug.AutoFlush = true;


                //Debug.Listeners.Clear();
                //sFile = string.Format("{0}{1}-{2}.log",Path.GetTempPath(), ProjectID, DateTime.Now.Second.ToString("00"));
                //TextWriterTraceListener tr2 = new TextWriterTraceListener(File.CreateText(sFile));
                //Debug.Listeners.Add(tr2);
                //Debug.AutoFlush = true;
            }


            //FormBaseLib.CCommon oTest = new FormBaseLib.CCommon();
            //oTest.Test1 = "1111";
            //string s1 = oTest.Test1;

            return true;
        }

        public static string ProductName
        {
            get { return Application.ProductName; }
        }
        public static string ProductVersion
        {
            get { return Application.ProductVersion; }
        }
        public static void ShowMsg(string sMsg)
        {
            mApp.mAction.AppendMsg(sMsg);
            if (!Program.gFMain.IsDisposed)
                Program.gFMain.ShowMsg(sMsg);
        }
        public static void ShowMsgError(string sMsg)
        {
            mApp.mAction.AppendMsgError(sMsg);
            if (!Program.gFMain.IsDisposed)
                Program.gFMain.ShowMsgError(sMsg);
        }
        public static bool AskMsg(string sMsg)
        {
            mApp.mAction.AppendMsgDebug(sMsg);
            return (MessageBox.Show(sMsg, ProductName, MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes);
        }

        public static string gByteToHex(byte b1)
        {
            // Example: Input 10, output "A".
            return string.Format("{0:X}", b1);
        }
        public static byte gHexToByte(string sHex)
        {
            // example: input "A", return 10.
            return byte.Parse(sHex, System.Globalization.NumberStyles.AllowHexSpecifier);
        }
        public static int gGetASCValue(char cUTF8)
        {
            return (System.Text.Encoding.UTF8.GetBytes(new char[] { cUTF8 }))[0];
        }
        public static char gGetAscChar(int iAsc)
        {
            // char c1 = '\u0001';
            // char c1 = (char) 1;
            return (char)iAsc;
        }
        public static byte gXOR(byte b1, byte b2)
        {
            // code helper
            //b1 ^= b2;
            //return b1;
            return Convert.ToByte(b1 ^ b2);
            //bXOR = 0;
            //for (int i = 1; i < 262; i++)
            //    bXOR = (byte)(bXOR ^ e.Data[i]);
        }
        public static long gGetDateTimeLong(DateTime dt)
        {
            return long.Parse(dt.ToString("yyyyMMddHHmmssfff"));
        }

        public static string gLeftString(string sInput, int iLen)
        {
            int iMyLen;
            if (string.IsNullOrEmpty(sInput))
                return string.Empty;

            if (iLen > sInput.Length)
                iMyLen = sInput.Length;
            else
                iMyLen = iLen;

            return sInput.Substring(0, iMyLen);
        }
        public static string gRightString(string sInput, int iLen)
        {
            int iMyLen;
            if (string.IsNullOrEmpty(sInput))
                return string.Empty;

            if (iLen > sInput.Length)
                iMyLen = sInput.Length;
            else
                iMyLen = iLen;

            return sInput.Substring(sInput.Length - iMyLen, iMyLen);
        }
        public static Form gShowForm(Type typeofForm)
        {
            Form fOpen = gGetOpenForm(typeofForm);
            Form fNew = null;
            if (fOpen == null)
                fNew = (Form)CreateNewInstanceOfType(typeofForm);
            else
                if (fOpen.IsDisposed)
                    fNew = (Form)CreateNewInstanceOfType(typeofForm);
                else
                    fNew = fOpen;

            fNew.Show();
            fNew.Focus();
            return fNew;
        }
        public static Form gShowFormFixedSingle(Type typeofForm, string sCaption, Form fMDIParent)
        {
            //DebugMsg("ShowForm() " + typeofForm.Name);
            Form fOpen = gGetOpenForm(typeofForm);
            Form fNew = null;
            //if (fNew == null)
            //    fNew = (Form)CreateNewInstanceOfType(typeofForm);
            //else
            //    if (fNew.IsDisposed)
            //        fNew = (Form)CreateNewInstanceOfType(typeofForm);

            if (fOpen == null)
                fNew = (Form)CreateNewInstanceOfType(typeofForm);
            else
                if (fOpen.IsDisposed)
                    fNew = (Form)CreateNewInstanceOfType(typeofForm);
                else
                    fNew = fOpen;

            if (fOpen == null) // new instance first time!
            {
                if (!string.IsNullOrEmpty(sCaption))
                    fNew.Text = sCaption;

                fNew.ControlBox = true;
                fNew.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
                fNew.MaximizeBox = false;
                fNew.MinimizeBox = false;
                if (fMDIParent != null)
                    if (fNew.MdiParent == null)
                        fNew.MdiParent = fMDIParent;
                //fNew.StartPosition = FormStartPosition.Manual;
                //fNew.Left = 0;
                //fNew.Top = 0;
                fNew.StartPosition = FormStartPosition.CenterScreen;
            }
            fNew.Show();
            fNew.Focus();
            return fNew;
        }
        public static Form gShowFormMDIChild(Type typeofForm, string sCaption, Form fMDIParent)
        {
            //DebugMsg("ShowForm() " + typeofForm.Name);
            Form fOpen = gGetOpenForm(typeofForm);
            Form fNew = null;
            //if (fNew == null)
            //    fNew = (Form)CreateNewInstanceOfType(typeofForm);
            //else
            //    if (fNew.IsDisposed)
            //        fNew = (Form)CreateNewInstanceOfType(typeofForm);

            if (fOpen == null)
                fNew = (Form)CreateNewInstanceOfType(typeofForm);
            else
                if (fOpen.IsDisposed)
                    fNew = (Form)CreateNewInstanceOfType(typeofForm);
                else
                    fNew = fOpen;

            if (fOpen == null) // new instance first time!
            {
                if (!string.IsNullOrEmpty(sCaption))
                    fNew.Text = sCaption;

                //fNew.ControlBox = true;
                //fNew.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
                //fNew.MaximizeBox = false;
                //fNew.MinimizeBox = false;
                if (fMDIParent != null)
                    if (fNew.MdiParent == null)
                        fNew.MdiParent = fMDIParent;
                //fNew.StartPosition = FormStartPosition.Manual;
                //fNew.Left = 0;
                //fNew.Top = 0;
                fNew.StartPosition = FormStartPosition.CenterScreen;
            }
            fNew.Show();
            fNew.Focus();
            return fNew;
        }

        public static Form gShowForm(Type typeofForm, string sCaption, Form fMDIParent)
        {
            //DebugMsg("ShowForm() " + typeofForm.Name);
            Form fOpen = gGetOpenForm(typeofForm);
            Form fNew = null;
            //if (fNew == null)
            //    fNew = (Form)CreateNewInstanceOfType(typeofForm);
            //else
            //    if (fNew.IsDisposed)
            //        fNew = (Form)CreateNewInstanceOfType(typeofForm);

            if (fOpen == null)
                fNew = (Form)CreateNewInstanceOfType(typeofForm);
            else
                if (fOpen.IsDisposed)
                    fNew = (Form)CreateNewInstanceOfType(typeofForm);
                else
                    fNew = fOpen;

            if (fOpen == null) // new instance first time!
            {
                if (!string.IsNullOrEmpty(sCaption))
                    fNew.Text = sCaption;

                //fNew.ControlBox = true;
                //fNew.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
                //fNew.MaximizeBox = false;
                //fNew.MinimizeBox = false;
                if (fMDIParent != null)
                    if (fNew.MdiParent == null)
                        fNew.MdiParent = fMDIParent;
                //fNew.StartPosition = FormStartPosition.Manual;
                //fNew.Left = 0;
                //fNew.Top = 0;
                fNew.StartPosition = FormStartPosition.CenterScreen;
            }
            fNew.Show();
            fNew.Focus();
            return fNew;
        }
        public static Form gGetOpenForm(Type typeofForm)
        {
            FormCollection fc = Application.OpenForms;
            foreach (Form f1 in fc)
                if (f1.GetType() == typeofForm)
                    return f1;

            return null;
        }
        public static object CreateNewInstanceOfType(Type typeofAny)
        {
            return Activator.CreateInstance(typeofAny);
        }
        public static string gBytesToStringUTF8(byte[] baInput)
        {
            return System.Text.Encoding.UTF8.GetString(baInput);
        }
        public static string gByteArrayToHex(byte[] baInput)
        {
            // code helper:
            // byte[] data = { 1, 2, 4, 8, 16, 32 };
            // string hex = BitConverter.ToString(data);
            // hex = 01-02-04-08-10-20
            // string hex = BitConverter.ToString(data).Replace("-", string.Empty);
            // hex = 010204081020
            //return BitConverter.ToString(ba1).Replace("-", string.Empty);
            return BitConverter.ToString(baInput);
        }
        public static string gStringToHex(string sInput)
        {
            return BitConverter.ToString(gStringToBytes(sInput));
        }
        public static string gStringASCToHex(string sInput)
        {
            return gByteArrayToHex(gStringUTF8ToBytes(sInput));
        }

        public static byte[] gStringToBytes(string str)
        {
            byte[] bytes = new byte[str.Length * sizeof(char)];
            System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
            return bytes;
        }
        public static byte[] gStringUTF8ToBytes(string sUTF8)
        {
            return (System.Text.Encoding.UTF8.GetBytes(sUTF8));
        }

        public static string gBytesToString(byte[] bytes)
        {
            char[] chars = new char[bytes.Length / sizeof(char)];
            System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
            return new string(chars);
        }
        public static string AssemblyTitle
        {
            get
            {
                object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyTitleAttribute), false);
                if (attributes.Length > 0)
                {
                    AssemblyTitleAttribute titleAttribute = (AssemblyTitleAttribute)attributes[0];
                    if (titleAttribute.Title != "")
                    {
                        return titleAttribute.Title;
                    }
                }
                return System.IO.Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().CodeBase);
            }
        }

        //public static string AssemblyVersion
        //{
        //    get
        //    {
        //        return Assembly.GetExecutingAssembly().GetName().Version.ToString();
        //    }
        //}
        public static string gCRLFForceTo(string sInput)
        {
            return gCRLFReplace(sInput, "\r\n");
        }
        public static string gCRLFRemove(string sInput)
        {
            return gCRLFReplace(sInput, string.Empty);
        }
        public static string gCRLFReplace(string sInput, string sToReplace)
        {
            return sInput.Replace("\r\n", "\n").Replace("\r", "\n").Replace("\n", sToReplace);
        }
        public static void gCboSetIndex(ComboBox cbo, string sInput)
        {
            int iIndex = 0;

            iIndex = cbo.Items.IndexOf(sInput);
            if (iIndex < 0)
                cbo.SelectedText = string.Empty; // 不要設成sinput, 導致誤解cbo.SelectedValue!

            cbo.SelectedIndex = iIndex;
        }
        public static int gCboGetIndex(ComboBox cbo, string sInput)
        {
            return cbo.Items.IndexOf(sInput);
        }
        public static int gCboGetIndex(ComboBox cbo, int iInput)
        {
            // 注意: items = ObjectCollection, 因此可存取數值...等非字串值陣列. (建議特殊情況才用, 因容易混淆!)
            return cbo.Items.IndexOf(iInput);
        }
        public static bool gGetEnumItem(Type TypeOfEnum1, string sItem, out object oEnumItem)
        {
            oEnumItem = null;
            if (string.IsNullOrEmpty(sItem))
                return false;

            if (!Enum.IsDefined(TypeOfEnum1, sItem))
                return false;

            oEnumItem = Enum.Parse(TypeOfEnum1, sItem);
            return true;
        }
        public static bool gGetEnumItem(Type TypeOfEnum1, int iInput, out object oEnumItem)
        {
            oEnumItem = null;

            if (!Enum.IsDefined(TypeOfEnum1, iInput))
                return false;

            oEnumItem = iInput;
            return true;
        }
        public static void gCboAddItem(ComboBox cbo, Type typeofEnum, bool bByName)
        {
            if (bByName)
            {
                foreach (string s in Enum.GetNames(typeofEnum))
                    cbo.Items.Add(s);
            }
            else
            {
                // keep in string format!
                foreach (int i in Enum.GetValues(typeofEnum))
                    cbo.Items.Add(i.ToString());
            }

        }

        public static void ShowDebugForm()
        {
            if (CProject.mApp.mbDebug)
            {
                FActionLog f1 = new FActionLog();
                f1.Show();
                f1.Focus();
            }
        }
    }
}
